<!-- src/view/guide/Profile.vue -->
<template>
  <div class="guide-profile">
    <h2 class="page-title">地陪个人中心</h2>
    <!--用户信息，为卡片格式card-->
    <el-card class="info-card">
      <div v-if="guideInfo">
        <el-descriptions title="个人信息" :column="2" border>
          <el-descriptions-item label="用户名">{{ guideInfo.username }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ guideInfo.gender === 0 ? '女' : '男' }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ guideInfo.phone }}</el-descriptions-item>
          <el-descriptions-item label="位置">{{ guideInfo.position }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ guideInfo.age }}</el-descriptions-item>
          <el-descriptions-item label="身高">{{ guideInfo.height }}cm</el-descriptions-item>
          <el-descriptions-item label="体重">{{ guideInfo.weight }}g</el-descriptions-item>
          <el-descriptions-item label="价格">{{ guideInfo.price }}元/天</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ guideInfo.email }}</el-descriptions-item>
        </el-descriptions>

        <!-- 照片展示 -->
        <div v-if="guideInfo.image" class="image-section">
          <el-text class="image-label">照片：</el-text>
          <el-image
              :src="getOssImageUrl(guideInfo.image)"
              class="profile-image"
              fit="cover"
              :preview-src-list="[getOssImageUrl(guideInfo.image)]">
          </el-image>
        </div>
      </div>

      <div v-else>
        <!--在需要等待加载内容的位置设置一个骨架屏-->
        <el-skeleton :rows="5" animated />
      </div>
    </el-card>

    <!-- 编辑功能 -->
    <el-card class="edit-card">
      <template #header>
        <div class="card-header">
          <span>编辑个人信息</span>
        </div>
      </template>
      <el-form :model="editForm" label-width="80px" class="edit-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input v-model="editForm.username"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="editForm.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option label="男" :value="1"></el-option>
                <el-option label="女" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号">
              <el-input v-model="editForm.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="位置">
              <el-input v-model="editForm.position"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="邮箱">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年龄">
              <el-input-number v-model="editForm.age" :min="1" :max="120"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身高(cm)">
              <el-input-number v-model="editForm.height" :min="1" :max="300"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="体重(g)">
              <el-input-number v-model="editForm.weight" :min="1" :max="300"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格(按天)">
              <el-input-number v-model="editForm.price" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="照片">
          <el-input v-model="editForm.image" readonly>
            <template #append>
              <el-button @click="handleImageUpload" class="upload-button">
                <el-icon><Upload /></el-icon> 上传
              </el-button>
            </template>
          </el-input>
          <div v-if="editForm.image" class="image-preview">
            <el-image
                :src="getOssImageUrl(editForm.image)"
                class="preview-image"
                fit="cover"
                :preview-src-list="[getOssImageUrl(editForm.image)]">
            </el-image>
          </div>
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button type="primary" @click="saveProfile" class="save-button">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>
      <el-form
          :model="passwordForm"
          ref="passwordFormRef"
          label-width="100px"
          class="password-form"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              show-password
              placeholder="请输入原密码"
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="passwordForm.newPassword"
              type="password"
              show-password
              placeholder="请输入新密码"
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              show-password
              placeholder="请再次输入新密码"
          />
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button
              type="primary"
              @click="changePassword"
              :loading="passwordLoading"
              class="change-password-button"
          >
            修改密码
          </el-button>
          <el-button @click="resetPasswordForm" class="reset-button">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传图片" width="500px" class="upload-dialog">
      <div class="upload-container">
        <input
            type="file"
            accept="image/*"
            @change="handleFileChange"
            ref="fileInput"
            style="display: none"
        >
        <el-button
            @click="$refs.fileInput.click()"
            type="primary"
            :loading="uploadLoading"
            class="upload-btn">
          <el-icon><Upload /></el-icon>
          {{ uploadLoading ? '上传中...' : '选择图片文件' }}
        </el-button>
        <p class="upload-tip">
          支持 JPG/PNG 格式
        </p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, reactive} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import g_guide_api from "@/api/guide/guide_api.js"
import uploadApi from "@/api/upload_api.js"
import {getJwtPayload} from "@/util/auth.js";
import guide_api from "@/api/guide/guide_api.js";
import {useRouter} from "vue-router";
// 引入AI聊天插件
import '../../ai-chat-plugin.js'

// 当前地陪信息
const guideInfo = ref(null)

// 编辑表单数据
const editForm = ref({
  username: '',
  gender: 1,
  phone: '',
  email: '',
  position: '',
  age: 0,
  height: 0,
  weight: 0,
  price: 0,
  image: ''
})

// 上传相关
const uploadDialogVisible = ref(false)
const uploadLoading = ref(false)

// 处理OSS图片URL
const getOssImageUrl = (imageUrl) => {
  // 如果没有图片URL，返回默认图片
  if (!imageUrl || imageUrl.trim() === '') {
    return 'https://via.placeholder.com/40x40?text=No+Image';
  }
  // 如果已经是完整URL，直接返回
  if (imageUrl.startsWith('http')) {
    return imageUrl;
  }
  // 如果是相对路径，构建完整URL
  const bucketName = 'java-dz';
  const endpoint = 'oss-cn-beijing.aliyuncs.com';
  return `https://${bucketName}.${endpoint}/${imageUrl}`;
}

// 页面加载时获取地陪信息
onMounted(async () => {
  await loadGuideProfile();
})

// 加载当前地陪信息
const loadGuideProfile = async () => {
  try {
    const payload = getJwtPayload();
    if (!payload || (payload.ID == null && payload.id)){
      throw new Error('未从 token 中读取到用户 ID');
    }
    const currentGuideId = Number(payload.ID ?? payload.id);

    const result = await g_guide_api.find(currentGuideId);
    guideInfo.value = result;
    editForm.value = { ...result };
  } catch (error) {
    console.error('获取地陪信息失败:', error);
    ElMessage.error('获取个人信息失败: ' + error.message);
  }
}

// 保存个人信息
const saveProfile = async () => {
  try {
    if (!editForm.value.id){
      editForm.value.id = guideInfo.value?.id ?? guideInfo.value?.ID;
    }
    await g_guide_api.edit(editForm.value);
    ElMessage.success('保存成功');

    // 保存成功后重新加载数据，更新上方卡片展示
    await loadGuideProfile();
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message);
  }
}

// 图片上传功能
const handleImageUpload = () => {
  uploadDialogVisible.value = true
}

const handleFileChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return
  }

  uploadLoading.value = true
  try {
    const result = await uploadApi.upload(file)
    console.log(result)

    if (!result || typeof result !== 'string') {
      throw new Error('上传失败：服务器未返回有效数据')
    }

    editForm.value.image = result
    ElMessage.success('上传成功')
    uploadDialogVisible.value = false
  } catch (error) {
    ElMessage.error('上传失败: ' + error.message)
  } finally {
    uploadLoading.value = false
    event.target.value = ''
  }
}

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 获取路由对象
const router = useRouter()
// 密码修改表单引用
const passwordFormRef = ref(null);
// 定义响应式数据
const passwordLoading = ref(false)

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return

  const valid = await passwordFormRef.value.validate()
  if (!valid) return

  passwordLoading.value = true

  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('未登录或登录已过期')
      passwordLoading.value = false
      return
    }

    // 使用manager_api调用修改密码接口
    const res = await guide_api.changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })

    // 添加调试日志
    console.log('修改密码响应:', res)
    console.log('响应类型:', typeof res)
    console.log('响应code:', res?.code)
    console.log('code === 200:', res?.code === 200)

    if (res && res.code === 200) {
      ElMessage.success('密码修改成功，请重新登录')
      resetPasswordForm()

      // 弹出确认框后跳转到登录页
      ElMessageBox.confirm('密码已修改，需要重新登录', '提示', {
        confirmButtonText: '确定',
        type: 'success',
        showCancelButton: false
      }).then(() => {
        // 清除token并跳转到登录页
        localStorage.removeItem('token')
        localStorage.removeItem('userRole')
        router.push('/login')
      })
    } else {
      ElMessage.error(res?.msg || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('密码修改失败: ' + (error.response?.data?.msg || error.message))
  } finally {
    passwordLoading.value = false
  }
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''

  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
}
</script>

<style scoped>
.guide-profile {
  padding: 20px;
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  min-height: 100%;
}

.page-title {
  color: #409eff;
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 20px 0;
  text-align: center;
  letter-spacing: 1px;
}

.info-card,
.edit-card,
.password-card {
  border-radius: 15px;
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.15);
  border: none;
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
}

:deep(.info-card .el-card__body),
:deep(.edit-card .el-card__body),
:deep(.password-card .el-card__body) {
  padding: 25px;
}

:deep(.edit-card .el-card__header),
:deep(.password-card .el-card__header) {
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  color: #409eff;
  border-radius: 15px 15px 0 0 !important;
  padding: 20px;
  border: none;
}

.card-header {
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
}

:deep(.el-descriptions__title) {
  color: #409eff;
  font-weight: 600;
}

:deep(.el-descriptions__label) {
  background-color: #f0f9ff !important;
  color: #409eff;
  font-weight: 500;
}

.image-section {
  margin-top: 20px;
}

.image-label {
  display: block;
  margin-bottom: 10px;
  color: #409eff;
  font-weight: 500;
}

.profile-image {
  width: 100px;
  height: 100px;
  border-radius: 10px;
  border: 2px solid #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.edit-form {
  margin-top: 20px;
}

:deep(.el-form-item__label) {
  color: #409eff;
  font-weight: 500;
}

.upload-button {
  background: linear-gradient(135deg, #409eff, #67c23a);
  border: none;
  color: white;
}

.image-preview {
  margin-top: 10px;
}

.preview-image {
  width: 100px;
  height: 100px;
  border-radius: 10px;
  border: 1px solid #d1e1ff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.form-actions {
  margin-top: 20px;
  text-align: center;
}

.save-button,
.change-password-button {
  background: linear-gradient(135deg, #409eff, #67c23a);
  border: none;
  font-weight: 600;
  letter-spacing: 1px;
  padding: 12px 30px;
}

.reset-button {
  margin-left: 15px;
  background: linear-gradient(135deg, #f0f9ff, #e6f7ff);
  border: 1px solid #409eff;
  color: #409eff;
  font-weight: 500;
}

.upload-dialog {
  border-radius: 15px;
  overflow: hidden;
}

:deep(.upload-dialog .el-dialog__header) {
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  color: #409eff;
  padding: 20px;
  border-radius: 15px 15px 0 0 !important;
}

:deep(.upload-dialog .el-dialog__title) {
  color: #409eff;
  font-weight: 600;
}

.upload-container {
  text-align: center;
  padding: 30px 20px;
}

.upload-btn {
  background: linear-gradient(135deg, #409eff, #67c23a);
  border: none;
  font-weight: 600;
  padding: 15px 30px;
  font-size: 16px;
}

.upload-tip {
  margin-top: 15px;
  color: #909399;
  font-size: 14px;
}

@media (max-width: 768px) {
  .guide-profile {
    padding: 15px;
  }

  .page-title {
    font-size: 24px;
  }

  :deep(.el-card__body) {
    padding: 20px;
  }

  .save-button,
  .change-password-button {
    width: 100%;
    margin-bottom: 10px;
  }

  .reset-button {
    width: 100%;
    margin-left: 0;
  }
}
</style>
